package com.yanqu.road.server.manager.union.honors;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eUnionSyncType;
import com.yanqu.road.entity.rank.UnionValueRank;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.entity.union.honors.UnionHistoryHonorsRecordData;
import com.yanqu.road.entity.union.honors.UnionHonorsPointData;
import com.yanqu.road.entity.union.honors.eHonorsActivityType;
import com.yanqu.road.logic.bussiness.union.cross.CrossUnionHonorsBussiness;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.pb.union.cross.CrossUnionHonorsProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityInfoMgr;
import com.yanqu.road.server.manager.config.GoodsMgr;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.server.manager.union.activitygroup.Cross3UnionActivityGroupMgr;
import com.yanqu.road.server.manger.ServerGroupMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionHonorsMgr extends TempMgr {

    /**
     * 商会荣誉点
     */
    static Map<String, List<UnionHonorsPointData>> unionHonorsPointMap;

    /**
     * 商会历史荣誉
     */
    static Map<String, List<UnionHistoryHonorsRecordData>> unionHistoryHonorsRecordMap;


    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {

        unionHonorsPointMap = CrossUnionHonorsBussiness.getUnionHonorsPointMap();

        unionHistoryHonorsRecordMap = CrossUnionHonorsBussiness.getUnionHistoryHonorsRecordMap();
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
        for (Map.Entry<String, List<UnionHonorsPointData>> entry : unionHonorsPointMap.entrySet()) {
            List<UnionHonorsPointData> list = entry.getValue();
            for (int i = 0; i < list.size(); i++) {
                UnionHonorsPointData data = list.get(i);
                if(data.isInsertOption()){
                    CrossUnionHonorsBussiness.addUnionHonorsPointData(data);
                }else if(data.isUpdateOption()){
                    CrossUnionHonorsBussiness.updateUnionHonorsPointData(data);
                }
            }
        }

        for (Map.Entry<String, List<UnionHistoryHonorsRecordData>> entry : unionHistoryHonorsRecordMap.entrySet()) {
            List<UnionHistoryHonorsRecordData> list = entry.getValue();
            for (int i = 0; i < list.size(); i++) {
                UnionHistoryHonorsRecordData data = list.get(i);
                if(data.isInsertOption()){
                    CrossUnionHonorsBussiness.addUnionHistoryHonorsRecordData(data);
                }else if(data.isUpdateOption()){
                    CrossUnionHonorsBussiness.updateUnionHistoryHonorsRecordData(data);
                }
            }
        }

        return true;
    }

    public static List<UnionHistoryHonorsRecordData> getHistoryHonorsRecordList(String unionUid){
        return unionHistoryHonorsRecordMap.get(unionUid);
    }

    public static UnionHistoryHonorsRecordData getUnionHistoryHonorsRecordData(String unionUid, int activityId){
        List<UnionHistoryHonorsRecordData> list = unionHistoryHonorsRecordMap.get(unionUid);
        if(list == null){
            return null;
        }
        for (UnionHistoryHonorsRecordData recordData : list) {
            if(recordData.getActivityId() == activityId){
                return recordData;
            }
        }
        return null;
    }

    public static boolean addUnionHistoryHonorsRecordData(UnionHistoryHonorsRecordData data){
        UnionHistoryHonorsRecordData added = getUnionHistoryHonorsRecordData(data.getUnionUid(), data.getActivityId());
        if(added != null){
            return false;
        }
        synchronized (unionHistoryHonorsRecordMap){
            added = getUnionHistoryHonorsRecordData(data.getUnionUid(), data.getActivityId());
            if(added != null){
                return false;
            }
            List<UnionHistoryHonorsRecordData> list = unionHistoryHonorsRecordMap.get(data.getUnionUid());
            if (list == null) {
                unionHistoryHonorsRecordMap.put(data.getUnionUid(), new ArrayList<>());
                list = unionHistoryHonorsRecordMap.get(data.getUnionUid());
            }
            list.add(data);
        }
        return true;
    }
    //变成道具直接添加了，一个活动可以添加多个了
    public static boolean addUnionHistoryHonorsRecordDataItem(UnionHistoryHonorsRecordData data){
        synchronized (unionHistoryHonorsRecordMap){
            List<UnionHistoryHonorsRecordData> list = unionHistoryHonorsRecordMap.get(data.getUnionUid());
            if (list == null) {
                unionHistoryHonorsRecordMap.put(data.getUnionUid(), new ArrayList<>());
                list = unionHistoryHonorsRecordMap.get(data.getUnionUid());
            }
            UnionHistoryHonorsRecordData old = getUnionHistoryHonorsRecordData(data.getUnionUid(), data.getActivityId());
            if(old == null) {
                list.add(data);
                attachUnionName(data);
            }else {
                old.setHonors(old.getHonors() + data.getHonors());
                old.setRank(data.getRank());
            }
        }
        return true;
    }

    /**
     * 获取参与商会
     */
    private static void attachUnionName(UnionHistoryHonorsRecordData data) {
        ActivityInfo activityInfo = ActivityInfoMgr.getActivityInfo(data.getActivityId());
        if (activityInfo != null && UnionActivityGroupHelper.needGroup(activityInfo)) {
            //锁名单的直接，那分组的商会
            int groupId = Cross3UnionActivityGroupMgr.getGroupId(data.getActivityId(), data.getUnionUid());
            UnionActivityGroup activityGroup = Cross3UnionActivityGroupMgr.getGroupData(data.getActivityId(), groupId);
            List<String> unionNameList = new ArrayList<>();
            if (activityGroup != null) {
                for (Map.Entry<String, UnionActivityGroupUnion> unionEntry : activityGroup.getUnionDataMap().entrySet()) {
                    UnionActivityGroupUnion union = unionEntry.getValue();
                    unionNameList.add(union.getUnionBaseInfo().getUnionName());
                }
            }
            data.setUnionNames(StringUtils.listToString(unionNameList, "@#$"));
        }
    }

    public static List<UnionHonorsPointData> getHonorsPointList(String unionUid){
        return unionHonorsPointMap.get(unionUid);
    }

    public static UnionHonorsPointData getUnionHonorsPointData(String unionUid, int activityType, int activityChildType){
        List<UnionHonorsPointData> list = getHonorsPointList(unionUid);
        if(list == null){
            return null;
        }
        for (UnionHonorsPointData data : list) {
            if(data.getActivityChildType() == activityChildType && data.getActivityType() == activityType){
                return data;
            }
        }
        return null;
    }

    public static void addUnionHonorsPointData(UnionHonorsPointData data){
        List<UnionHonorsPointData> list = unionHonorsPointMap.get(data.getUnionUid());
        if(list == null){
            synchronized (unionHonorsPointMap){
                list = unionHonorsPointMap.get(data.getUnionUid());
                if(list == null){
                    unionHonorsPointMap.put(data.getUnionUid(), new ArrayList<>());
                    list = unionHonorsPointMap.get(data.getUnionUid());
                }
            }
        }
        synchronized (list){
            list.add(data);
        }
    }

    /**
     * 增加荣誉
     */
    public static void addUnionHonorsPointData(UnionHistoryHonorsRecordData recordData) {
        UnionHonorsPointData pointData;
        synchronized (unionHonorsPointMap) {
            pointData = getUnionHonorsPointData(recordData.getUnionUid(), recordData.getActivityType(), recordData.getActivityChildType());
            if(pointData == null){
                pointData = new UnionHonorsPointData();
                pointData.setInsertOption();
                pointData.setUnionUid(recordData.getUnionUid());
                pointData.setActivityType(recordData.getActivityType());
                pointData.setActivityChildType(recordData.getActivityChildType());
            }
            pointData.setLastUpdateTime(DateHelper.getCurrentSecond());
            pointData.setHonors(pointData.getHonors() + recordData.getHonors());
            if(pointData.isInsertOption()){
                addUnionHonorsPointData(pointData);
            }
        }

        unlockFlag(pointData.getUnionUid(), pointData.getActivityType(), pointData.getActivityChildType(), pointData.getHonors());

        CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(recordData.getUnionUid());
        if(unionInfo != null){
            List<UnionHonorsPointData> pointList = getHonorsPointList(unionInfo.getUnionUid());
            if(pointList != null){
                long honors = 0;
                for (UnionHonorsPointData data : pointList) {
                    honors += data.getHonors();
                }
                unionInfo.setHonors(honors);

                //榜单
                UnionValueRank unionRank = CrossUnionMgr.pareUnionInfoToUnionValueRank(unionInfo);
                CrossUnionHonorsRankMgr.changeUnionRank(unionInfo.getServerId(), unionRank);

                CrossUnionMgr.sendUnionChangeBroadcast(eUnionSyncType.Normal.getValue(), unionInfo, null, null, 0);
            }
        }

        syncHonorsPointMsg(recordData.getUnionUid());
    }

    //道具添加荣誉点，不能用这个recordData来,这个会固定死加到哪里，要用道具
    public static void addUnionHonorsPointDataItem(UnionHistoryHonorsRecordData recordData) {
        UnionHonorsPointData pointData;
        synchronized (unionHonorsPointMap) {
            GoodsInfo goodsInfo = GoodsMgr.getGoodsInfo(recordData.getGoodId());
            if(goodsInfo != null){
                eHonorsActivityType honorsActivityType = eHonorsActivityType.getHonorsType(goodsInfo.getParamList().get(0).intValue());
                if(honorsActivityType != null){
                    pointData = getUnionHonorsPointData(recordData.getUnionUid(), honorsActivityType.getActivityType(), honorsActivityType.getActivityChildType());
                    if(pointData == null){
                        pointData = new UnionHonorsPointData();
                        pointData.setInsertOption();
                        pointData.setUnionUid(recordData.getUnionUid());
                        pointData.setActivityType(honorsActivityType.getActivityType());
                        pointData.setActivityChildType(honorsActivityType.getActivityChildType());
                    }
                    pointData.setLastUpdateTime(DateHelper.getCurrentSecond());
                    pointData.setHonors(pointData.getHonors() + recordData.getHonors());
                    if(pointData.isInsertOption()){
                        addUnionHonorsPointData(pointData);
                    }
                }else{
                    return;
                }
            }else{
                return;
            }
        }

        unlockFlag(pointData.getUnionUid(), pointData.getActivityType(), pointData.getActivityChildType(), pointData.getHonors());

        CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(recordData.getUnionUid());
        if(unionInfo != null){
            List<UnionHonorsPointData> pointList = getHonorsPointList(unionInfo.getUnionUid());
            if(pointList != null){
                long honors = 0;
                for (UnionHonorsPointData data : pointList) {
                    honors += data.getHonors();
                }
                unionInfo.setHonors(honors);

                //榜单
                UnionValueRank unionRank = CrossUnionMgr.pareUnionInfoToUnionValueRank(unionInfo);
                CrossUnionHonorsRankMgr.changeUnionRank(unionInfo.getServerId(), unionRank);

                CrossUnionMgr.sendUnionChangeBroadcast(eUnionSyncType.Normal.getValue(), unionInfo, null, null, 0);
            }
        }

        syncHonorsPointMsg(recordData.getUnionUid());
    }

    /**
     * 增加荣誉记录
     */
    public static void addHonorsRecord(UnionHistoryHonorsRecordData recordData) {
        getLogger().debug("addHonorsRecord {}", JSON.toJSONString(recordData));
        boolean canAdd = addUnionHistoryHonorsRecordData(recordData);
        if(!canAdd){
            return;
        }

        addUnionHonorsPointData(recordData);
    }

    public static void addHonorsRecordItem(UnionHistoryHonorsRecordData recordData) {
        getLogger().debug("new addHonorsRecord {}", JSON.toJSONString(recordData));
        //策划说了只会配一个道具加一次就不会加了
        addUnionHistoryHonorsRecordDataItem(recordData);
        addUnionHonorsPointDataItem(recordData);
    }

    private static void syncHonorsPointMsg(String unionUid) {
        //同步最新荣誉点
        List<UnionHonorsPointData> list = CrossUnionHonorsMgr.getHonorsPointList(unionUid);
        if(list != null){
            CrossUnionHonorsProto.UnionHonorsPointListSync.Builder syncMsg = CrossUnionHonorsProto.UnionHonorsPointListSync.newBuilder();
            for (UnionHonorsPointData data : list) {
                CrossUnionHonorsProto.UnionHonorsPointTemp.Builder builder = builderHonors(data);
                syncMsg.addPoint(builder);
            }
            Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
            if(memberMap != null){
                for (Map.Entry<Long, CrossUnionMember> memberEntry : memberMap.entrySet()) {
                    CrossUnionMember member = memberEntry.getValue();
                    MessageHelper.sendPacket(member.getServerId(), member.getUserId(), YanQuMessageUtils.buildMessage(Protocol.U_UNION_UNION_HONORS_POINT_SYNC, syncMsg));
                }
            }
        }
    }

    private static CrossUnionHonorsProto.UnionHonorsPointTemp.Builder builderHonors(UnionHonorsPointData data) {
        CrossUnionHonorsProto.UnionHonorsPointTemp.Builder builder = CrossUnionHonorsProto.UnionHonorsPointTemp.newBuilder();
        builder.setActivityChildType(data.getActivityChildType());
        builder.setActivityType(data.getActivityType());
        builder.setHonors(data.getHonors());
        builder.setLastUpdateTime(data.getLastUpdateTime());
        return builder;
    }

    private static void unlockFlag(String unionUid, int activityType, int activityChildType, long honors) {
        //解锁旗帜
        List<Integer> newFlagIdList = new ArrayList<>();
        List<Integer> removeFlagIdList = new ArrayList<>();
        eHonorsActivityType eActivityType = eHonorsActivityType.getHonorsType(activityType, activityChildType);
        int honorsType = eActivityType.getHonorsType();
        List<GoodsInfo> list = GoodsMgr.getHonorsFlag(honorsType);
        if(list != null){
            for (GoodsInfo goodsInfo : list) {
                if(honors >= goodsInfo.getParamList().get(1).intValue()){
                    newFlagIdList.add(goodsInfo.getGoodsId());
                }else{
                    //变成道具了，可以扣除荣誉值，对应的棋子设置成过期
                    removeFlagIdList.add(goodsInfo.getGoodsId());
                }
            }
        }
        if(newFlagIdList.size() > 0){
            boolean addNew = false;
            for (int flagId : newFlagIdList) {
                addNew = CrossUnionMgr.addUnionFlag(unionUid, flagId) || addNew;
            }
            if(addNew){

            }
        }
        if(removeFlagIdList.size() > 0){
            for (int flagId : removeFlagIdList) {
                CrossUnionMgr.removeUnionFlag(unionUid, flagId);
            }
            CrossUnionMgr.changeUnionFlagByRemove(unionUid,removeFlagIdList);

        }
    }


    public static Map<Integer, LinkedList<UnionValueRank>> buildGroupRankData() {
        Map<Integer, LinkedList<UnionValueRank>> resultMap = new ConcurrentHashMap<>();

        for (Map.Entry<String, CrossUnionInfo> unionInfoEntry : CrossUnionMgr.getUnionInfoMap().entrySet()) {
            CrossUnionInfo unionInfo = unionInfoEntry.getValue();
            if(unionInfo.getHonors() == 0){
                continue;
            }
            int groupId = ServerGroupMgr.getGroupIdByServerId(unionInfo.getServerId());
            if(resultMap.get(groupId) == null){
                resultMap.put(groupId, new LinkedList<>());
            }
            UnionValueRank unionRank = CrossUnionMgr.pareUnionInfoToUnionValueRank(unionInfo);
            resultMap.get(groupId).add(unionRank);
        }

        return resultMap;
    }
}
